package com.limh.socketdemo.service.client

import android.util.Log
import com.limh.socketdemo.bean.MsgEvent
import com.limh.socketdemo.service.WebConfiguration
import com.limh.socketdemo.service.utils.StreamToolkit
import com.limh.socketdemo.utils.GsonUtils
import org.greenrobot.eventbus.EventBus
import java.io.IOException
import java.io.OutputStreamWriter
import java.net.Socket

/**
 * @function
 * @author limh
 * @date 2018/5/1 22:48
 */
class HttpClient(var webConfig: WebConfiguration) {

    private val TAG = "HttpClient"

    fun send(path: String, data: String) {
        Thread(Runnable {
            try {
                val socket = Socket(webConfig.address, webConfig.port)
                socket.soTimeout = 10000
                val osw = OutputStreamWriter(socket.getOutputStream(),Charsets.UTF_8)
                val sb = StringBuilder()
                sb.append("GET $path HTTP/1.1\r\n")
                sb.append("Host:${webConfig.address}\r\n")
                sb.append("Connection:Keep-Alive\r\n")
                sb.append("user-agent:1601\r\n")
                sb.append("Accept-Language:zh-CN,zh;q=0.9\r\n")
                sb.append("\r\n")
                sb.append("$data\r\n")
                osw.write(sb.toString())
                osw.flush()
                Log.e(TAG,"客户端发出的消息=$sb")
                val ins = socket.getInputStream()
                var headLine = ""
                while (StreamToolkit.readLine(ins).apply { headLine = this!! } != null) {
                    if (headLine == "\r\n"||headLine=="\uFFFF") {
                        Log.e(TAG, "header line finish:$headLine")
                        break
                    }
                    Log.e(TAG, "header line=$headLine")
                }

                var readLine=""
                while (StreamToolkit.readContent(ins).apply { readLine = this!! } != null) {
                    if (readLine == "") {
                        Log.d(TAG, "header line finish")
                        break
                    }
                    Log.i(TAG, "客户端收到消息内容=$readLine")
                    val msg = GsonUtils.str2Bean(readLine, MsgEvent::class.java)
                    EventBus.getDefault().post(msg)
                }

                ins.close()
                socket.close()
            } catch (e: IOException) {
                Log.e(TAG, "send error:${e.message}")
            }
        }).start()
    }

}